package com.example.yangyinzhaixian.uitl;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 *
 * @Description: 加密
 * @author
 * @2015-5-19
 *
 */
public class MD5Utils {
	/**
	 *
	 * @Description: 把指定字符串 按特定格式加密（UTF-8编码格式下使用）
	 * @param str
	 *            需要加密的字符串
	 * @return
	 */
	public static String Md5(String str) {
		if (str != null && !str.equals("")) {
			try {
				MessageDigest md5 = MessageDigest.getInstance("MD5");
				char[] HEX = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
						'9', 'a', 'b', 'c', 'd', 'e', 'f' };
				byte[] md5Byte = md5.digest(str.getBytes("UTF8"));
				StringBuffer sb = new StringBuffer();
				for (int i = 0; i < md5Byte.length; i++) {
					sb.append(HEX[(int) (md5Byte[i] & 0xff) / 16]);
					sb.append(HEX[(int) (md5Byte[i] & 0xff) % 16]);
				}
				str = sb.toString();
			} catch (NoSuchAlgorithmException e) {
			} catch (Exception e) {
			}
		}
		return str;
	}

	/**
	 *
	 * @Description: 把指定字符串 按特定格式加密（默认编码格式下使用）
	 * @paramstr
	 *            需要加密的字符串
	 * @return
	 */
	public final static String getMessageDigest(byte[] buffer) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			MessageDigest mdTemp = MessageDigest.getInstance("MD5");
			mdTemp.update(buffer);
			byte[] md = mdTemp.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 根据时间戳取得md5值
	 *
	 * @param base
	 *            为手机谍报馆的固定值:
	 * @param timestamp
	 *            当前时间戳
	 * @return token1的值
	 */
	public static String getToken1(String base, String timestamp) {
		String str = base + timestamp;
		System.out.println("base=" + base);
		System.out.println("timestamp=" + timestamp);
		System.out.println("str=" + str);
		try {
			MessageDigest digest = MessageDigest.getInstance("md5");
			digest.update(str.getBytes());
			byte[] result = digest.digest();
			StringBuilder sb = new StringBuilder();
			for (byte b : result) {
				sb.append(Integer.toHexString(b >>> 4 & 0x0f));
				sb.append(Integer.toHexString(b & 0x0f));
			}
			return sb.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}
}
